# _*_ coding:utf-8 _*_
import os

from oss2 import SizedFileAdapter, determine_part_size
from oss2.models import PartInfo
import oss2

access_key_id = ''
access_key_secret = ''
endpoint = ''
bucket_name = ''
oss_connect_time = '1'

key = 'oss_file.txt'
filename = 'local.txt'
total_size = os.path.getsize(filename)
part_size = determine_part_size(total_size, preferred_size=10000 * 1024)
# 初始化分片
bucket = oss2.Bucket(oss2.Auth(access_key_id, access_key_secret),
                     endpoint, bucket_name, connect_timeout=oss_connect_time)

upload_id = bucket.init_multipart_upload(key).upload_id
parts = []
# 逐个上传分片
with open(filename, 'rb') as fileobj:
    part_number = 1
    offset = 0
    while offset < total_size:
        rate = int(100 * float(offset) / float(total_size))
        print('\r{0}%'.format(rate))
        num_to_upload = min(part_size, total_size - offset)
        result = bucket.upload_part(key, upload_id, part_number,
                                    SizedFileAdapter(fileobj, num_to_upload))
        parts.append(PartInfo(part_number, result.etag))
        offset += num_to_upload
        part_number += 1
        print(part_number)
# 完成分片上传
bucket.complete_multipart_upload(key, upload_id, parts)
# 验证一下
exist = bucket.object_exists(key)
if exist:
    print("ok")
else:
    print("field")